package com.wlstock.funi.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.model.SelfFundSetModel;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SelfFundDao {
	
	private DataBaseHelper dbHelper;
	private static SelfFundDao daoInstance;
	private Dao<SelfFundModel, Integer> selfDao;
	
	@SuppressWarnings("unchecked")
	private SelfFundDao(Context mContext){
		try {
			dbHelper = DataBaseHelper.getHelper(mContext);
			selfDao = dbHelper.getDao(SelfFundModel.class);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static SelfFundDao getInstance(Context mContext){
		if (daoInstance == null) {
			synchronized (SelfFundDao.class) {
				if (daoInstance == null) {
					daoInstance = new SelfFundDao(mContext);
				}
			}
		}
		return daoInstance;
	}
	
	/**
	 * 需要判断 mode的 detailId 是否为空;
	 * @param mode
	 * @return
	 */
	public boolean addWithOperateMode(OperateModel mode){
		
		 try {
//			SelfFundModel queryR = selfDao.queryBuilder().where().eq("fundid",mode.getFundid()).queryForFirst();
			selfDao.updateRaw("delete from selffundmodel where fundid = ? and tradeType = ? ", new String[]{String.valueOf(mode.getFundid()),String.valueOf(mode.getTradeType()) });
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (mode.getStockHoldDetailId() != null) {
			SelfFundModel model = new SelfFundModel(mode);
			addOrUpdateSelfModel(model);
		}
		return false;
	}

	public void addOrUpdateSelfModel(SelfFundModel model) {
		try {
			selfDao.createOrUpdate(model);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addOrUpdateSelfModel(String stkCode, String stkName, String tagName){
		SelfFundModel sfModel = new SelfFundModel();
		sfModel.setStockNo(stkCode);
		sfModel.setStockName(stkName);
		sfModel.setTag(tagName);
		sfModel.setSourceCode(SelfFundModel.SOURCE_CUSTOMADD);
		addOrUpdateSelfModel(sfModel);
	}
	
	/**
	 * 事务操作添加opeartelist
	 * @param modes
	 * 
	 * 这个删除，原因是只需要在买入、卖出的时候执行操作即可，这样不需要每次都进行数据库操作。
	 * 而且方便加入某些删除操作
	 */
	public void addWithOperateModeList(final List<OperateModel> modes){
	    
			try {
				TransactionManager.callInTransaction(dbHelper.getConnectionSource(), new Callable<Void>() {
				    @Override
				    public Void call() throws Exception {
				        // TODO Auto-generated method stub
				    	
				    	LinkedHashMap<String, OperateModel> tempHash = new LinkedHashMap<String, OperateModel>();
				    	
				    	//优先存放今天到operatemode，暂时只考虑最近2天的操作
				        for (OperateModel operateModel : modes) {
				        	if (tempHash.get(operateModel.getStockNo())!=null) {
				        		//如果不为空，取这只最近的操作
				        		OperateModel tmpMode = tempHash.get(operateModel.getStockNo());
				        		if (operateModel.getTradedDate().getTime()>tmpMode.getTradedDate().getTime()) {
									tempHash.put(operateModel.getStockNo(), operateModel);	
								};
							}else {
								//如果tmphash为空，则直接存到里面去
								tempHash.put(operateModel.getStockNo(), operateModel);
							}
						}
				        
				        Iterator<Entry<String, OperateModel>> iterator = tempHash.entrySet().iterator();
				        while (iterator.hasNext()) {
							Map.Entry entry = (Map.Entry) iterator.next();
							daoInstance.addWithOperateMode((OperateModel) entry.getValue());
						}
						return null;
				    }
				});
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
	}
	

	/**
	 * 
	 * @return 我的自选所有的股票代码
	 */
	public ArrayList<String> queryAllSelfFundStkNos(){
		ArrayList<String> queryResults = new ArrayList<String>();
		try {
			GenericRawResults<String[]> rawResults = selfDao.queryRaw("select stockNo from SelfFundModel");
			ArrayList<String[]> results = (ArrayList<String[]>) rawResults.getResults();
			for (String[] strings : results) {
				queryResults.add(strings[0]);
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return queryResults;
	}
	
	/**
	 * 根据stkno获取sfmodel
	 * @param stkNo
	 * @return
	 */
	public SelfFundModel querySelfFundModel(String stkNo){
		try {
			SelfFundModel sfModel = selfDao.queryBuilder().where().eq("stockNo", stkNo).queryForFirst();
			return sfModel;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 根据stkno模糊搜索自选股
	 * @param stkNo
	 * @return
	 */
	public List<SelfFundModel> querySelfFundModelsLike(String stkNo){
		try {
			return selfDao.queryBuilder().where().like("stockNo", "%"+stkNo+"%").query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询所有的自选股的内容
	 * @return
	 */
	public List<SelfFundModel> queryAllSelfFundModes(){
		List<SelfFundModel> models = null;
		try {
			models = selfDao.queryBuilder().query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return models;
	}
	
	/**
	 * 查询某个标签的自选
	 */
	public List<SelfFundModel> queryFundModelsWithType(int sourceCode){
		List<SelfFundModel> models = null;
		try {
			models = selfDao.queryBuilder().where().eq("sourceCode", sourceCode).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return models;
	}
	
	/**
	 * 查询非某个标签的
	 * @param sourceCode
	 * @return
	 */
	public List<SelfFundModel> queryFundModelsExceptType(int sourceCode){
		List<SelfFundModel> models = null;
		try {
			models = selfDao.queryBuilder().where().ne("sourceCode", sourceCode).query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return models;
	}
	
	public List<SelfFundModel> parseSinaMultiPrices(String result, List<SelfFundModel> models){
//		var hq_str_sh600766="园城黄金,16.700,17.260,15.530,17.150,15.530,15.530,15.540,9534939,153943523.000,272021,15.530,0,0.000,0,0.000,0,0.000,0,0.000,8300,15.540,9800,15.560,5400,15.580,9200,15.590,1900,15.600,2016-01-11,15:00:00,00";
//		var hq_str_sh600498="烽火通信,29.760,30.980,27.880,29.760,27.880,0.000,27.880,32221016,921856300.000,0,0.000,0,0.000,0,0.000,0,0.000,0,0.000,1830100,27.880,44000,27.890,8300,27.900,3100,27.920,400,27.930,2016-01-11,15:00:00,00";
		
		if (models!=null && models.size()>0) {
			int size = models.size();
			Pattern compile = Pattern.compile("[0-9](.)*");
			Matcher matcher = compile.matcher(result);
			
			while(matcher.find()){
				//开盘，昨收，现价，最高，最低，
//				600175="美都能源,7.600,7.740,6.970,7.690,6.970,0.000,6.970,
//				121046327,886900917.000,0,0.000,0,0.000,0,0.000,0,0.000,0,0.000,1330700,6.970,378100,6.980,257700,6.990,51501,7.000,10700,7.010,2016-01-11,15:00:00,00";
				String tmp = result.substring(matcher.start(), matcher.end());
				String[] split = tmp.split("=");
				String stkNo = split[0];
				for (int i = 0; i < size; i++) {
					SelfFundModel sfModel = models.get(i);
					if (sfModel!=null && sfModel.getStockNo().equals(stkNo)) {
						String info = split[1].substring(1, split[1].length()-2);
						String[] detail = info.split(",");
						if (detail!=null && detail.length > 5) {
							sfModel.setStockName(detail[0]);
							sfModel.setCurOpen(Float.valueOf(detail[1]));
							sfModel.setlastClose(Float.valueOf(detail[2]));
							sfModel.setCurPrice(Float.valueOf(detail[3]));
							sfModel.sethPrice(Float.valueOf(detail[4]));
							sfModel.setLowPrice(Float.valueOf(detail[5]));	
						}
						break;
					}
				}
			}
		}
		return models;
	}

	
	
	public void addWithMyAccountStock(MyAccountStocks acStock) {
		// TODO Auto-generated method stub
		SelfFundModel model = new SelfFundModel(acStock);
		addOrUpdateSelfModel(model);

	} 
	
	/**
	 * 根据代码删除
	 * @param stkNo
	 */
	public void deleteWithStkNo(String stkNo){
		try {
			DeleteBuilder<SelfFundModel, Integer> deleteBuilder = selfDao.deleteBuilder();
			deleteBuilder.where().eq("stockNo", stkNo);
			deleteBuilder.delete();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据设置
	 * @param sfSetModels
	 */
	public void deleteWitnInvalidPendList(List<SelfFundSetModel> sfSetModels){
		if (sfSetModels == null || sfSetModels.size()==0) {
			return;
		}
		for (int i = 0; i < sfSetModels.size(); i++) {
			SelfFundSetModel sfSetModel = sfSetModels.get(i);
			this.deleteWithStkNo(sfSetModel.getStkNo());
		}
	}

	/**
	 * 通过标签查询
	 * @param tagName
	 */
	public List<SelfFundModel> queryFundModelsWithTag(String tagName) {
		try {
			return selfDao.queryBuilder().where().eq("tag",tagName).and().eq("sourceCode",SelfFundModel.SOURCE_CUSTOMADD).query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询除了万隆以外的所有股票的实时情况
	 * @return
     */
	public List<SelfFundModel> querySelfFundeModesExceptWanglong() {
		try {
			return  selfDao.queryBuilder().where().ne("sourceCode",SelfFundModel.SOURCE_WANGLONG).query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return  null;
	}

	/**
	 * 根据来源删除自选
	 * @param sourceCode
     */
	public void deleteWithSourceCode(int sourceCode) {
		try {
			int i = selfDao.updateRaw("delete from SelfFundModel where sourceCode = ?", String.valueOf(sourceCode));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
